package net.wanglu.www.spdr.fixer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import net.wanglu.www.spdr.entities.Corpus;

import org.apache.commons.lang3.text.StrBuilder;

public class HtmlEntityFixer implements Fixer{

	public static HashMap<String, String> HtmlEntity = new HashMap<String, String>(64);
	
	static {
		HtmlEntity.put("&nbsp;", " ");
		HtmlEntity.put("&#160;", " ");
		HtmlEntity.put("&lt;", "<");
		HtmlEntity.put("&#060", "<");
		HtmlEntity.put("&gt;", ">");
		HtmlEntity.put("&#062;", ">");
		HtmlEntity.put("&amp;", "&");
		HtmlEntity.put("&#038;", "&");
		HtmlEntity.put("&quot;", "\"");
		HtmlEntity.put("&#034;", "\"");
		HtmlEntity.put("&apos;", "'");
		HtmlEntity.put("&#039;", "'");
		HtmlEntity.put("&cent;", "￠");
		HtmlEntity.put("&#162;", "￠");
		HtmlEntity.put("&pound;", "£");
		HtmlEntity.put("&#163;", "£");
		HtmlEntity.put("&yen;", "¥");
		HtmlEntity.put("&#165;", "¥");
		HtmlEntity.put("&sect;", "§");
		HtmlEntity.put("&copy;", "©");
		HtmlEntity.put("&#167;", "©");
		HtmlEntity.put("&reg;", "®");
		HtmlEntity.put("&#174;", "®");
		HtmlEntity.put("&times;", "×");
		HtmlEntity.put("&#215;", "×");
		HtmlEntity.put("&divide;", "÷");
		HtmlEntity.put("&#247;", "÷");
	}
	@Override
	public Corpus fix(Corpus corpus) throws Exception {
		// TODO Auto-generated method stub
		String title = fixEntity(corpus.getTitle());
		String abstracts = fixEntity(corpus.getAbstracts());
		ArrayList<String> text = corpus.getText();
		ArrayList<String> newText = new ArrayList<String>(text.size()*4/3);
		for ( int i=0; i<text.size(); i++ ) {
			String str = fixEntity(text.get(i));
			newText.add(str);
		}
		text.clear();
		text = null;
		corpus.setTitle(title);
		corpus.setAbstracts(abstracts);
		corpus.setText(newText);
		return corpus;
	}

	private String fixEntity(String text) {
		Set<String> keys = HtmlEntity.keySet();
		StrBuilder sb = new StrBuilder(text);
		for(Iterator<String> itr = keys.iterator(); itr.hasNext(); ){
			String key = itr.next();
			String value = HtmlEntity.get(key);
			sb.replaceAll(key, value);
		}
		return sb.trim().toString();
	}
}
